<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>counter</title>
</head>

<body>
    <div id="counter"></div>
    <button id="btn" type="button">点击我重新计数</button>
    <script>
        const counter = (selector, start, end, step = 1, duration = 2000) => {
            const $ = v => document.querySelector(v);
            let current = start,
                _step = (end - start) * step < 0 ? -step : step,
                timer = setInterval(() => {
                    current += _step;
                    $(selector).innerHTML = current;
                    if (current >= end) {
                        $(selector).innerHTML = end;
                        clearInterval(timer);
                    }
                }, Math.abs(Math.floor(duration / (end - start))));
            return timer;
        };
        counter('#counter', 1, 1000, 5, 2000);
        const btn = document.querySelector('#btn');
        btn.onclick = () => counter('#counter', 1, 1000, 5, 2000);
    </script>
</body>

</html>